<template>
  <div ref="pie" :class="className" :style="{ height: height, width: width }"></div>
</template>

<script setup>
import * as echarts from 'echarts/core'
import { ToolboxComponent, LegendComponent } from 'echarts/components'
import { PieChart } from 'echarts/charts'
import { LabelLayout } from 'echarts/features'
import { CanvasRenderer } from 'echarts/renderers'
import { debounce } from 'lodash'
import 'echarts/theme/macarons'

echarts.use([ToolboxComponent, LegendComponent, PieChart, CanvasRenderer, LabelLayout])

defineProps({
  className: {
    type: String,
    default: 'chart'
  },
  width: {
    type: String,
    default: '100%'
  },
  height: {
    type: String,
    default: '100%'
  }
})
let chart = null
const pie = ref(null)

function initChart() {
  chart = echarts.init(pie.value, 'macarons')

  chart.setOption({
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b} : {c} ({d}%)'
    },
    calculable: true,
    series: [
      {
        name: '学科分布',
        type: 'pie',
        roseType: 'radius',
        radius: [15, 50],
        center: ['50%', '50%'],
        data: [
          { value: 320, name: '前端' },
          { value: 240, name: 'java' },
          { value: 149, name: 'python' },
          { value: 100, name: 'c++' },
          { value: 59, name: 'UI' }
        ],
        animationEasing: 'cubicInOut',
        animationDuration: 2600
      }
    ]
  })
}

const __resizeHandler = debounce(() => {
  if (chart.value) {
    chart.value.resize()
  }
}, 100)
onMounted(() => {
  initChart()

  window.addEventListener('resize', __resizeHandler)
})

onBeforeUnmount(() => {
  if (!chart) {
    return
  }
  window.removeEventListener('resize', __resizeHandler)
  chart.dispose()
  chart = null
})
</script>
